package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.model.H5LoginUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 基于主体类型的鉴权评估器。
 * 用法示例：@PreAuthorize("@userType.isH5()") 或 @PreAuthorize("@userType.isSys()")
 */
@Component("userType")
public class UserTypeEvaluator {

    /**
     * 当前认证主体是否为 H5 用户
     */
    public boolean isH5() {
        Object principal = getPrincipal();
        return principal instanceof H5LoginUser;
    }

    /**
     * 当前认证主体是否为后台（设计师/管理员）用户
     */
    public boolean isSys() {
        Object principal = getPrincipal();
        return principal instanceof LoginUser;
    }

    /**
     * 当前主体是否在给定集合中（可传入 "H5" 或 "SYS"）
     */
    public boolean hasAny(String... types) {
        boolean h5 = isH5();
        boolean sys = isSys();
        if (types == null) return false;
        for (String t : types) {
            if (t == null) continue;
            String v = t.trim().toUpperCase();
            if ((h5 && "H5".equals(v)) || (sys && ("SYS".equals(v) || "ADMIN".equals(v)))) {
                return true;
            }
        }
        return false;
    }

    private Object getPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication == null ? null : authentication.getPrincipal();
    }
}


